package org.jeecg.access.Controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.access.entity.PlatformAccount;
import org.jeecg.access.platform.constant.DataState;
import org.jeecg.access.platform.service.PlatformHandler;
import org.jeecg.access.service.PlatformAccountService;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.UUIDGenerator;

import org.jeecg.config.PlatformHandlerFactory;
import org.jeecg.util.DateTimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 平台账户管理控制器
 */
@Slf4j
@RestController
@RequestMapping("/platformAccount")
@Api(tags = "平台的账号管理")
public class PlatformAccountController {

    private final PlatformAccountService platformAccountService;


    private final PlatformHandlerFactory handlerFactory;

    @Autowired
    public PlatformAccountController(PlatformAccountService platformAccountService,
                                     PlatformHandlerFactory handlerFactory) {
        this.platformAccountService = platformAccountService;
        this.handlerFactory = handlerFactory;
    }

    /**
     * 添加平台账户
     */
    /**
     * 添加平台账户
     */
    @PostMapping("/add")
    @ApiOperation("添加平台账户")
    public Result<Object> add(@RequestBody PlatformAccount account) {
        try {
            // 1. 基础数据校验
            String validateMsg = validateAccount(account);
            if (validateMsg != null) {
                return Result.error(validateMsg);
            }

            PlatformHandler handler = handlerFactory.getHandler(account.getPlatformType());
            validateMsg = handler.verifyAddedAccount(account);

            if (validateMsg != null) {
                return Result.error(validateMsg);
            }

            // 3. 设置基础字段
            String username = getCurrentUsername();
            String nowTime = DateTimeUtil.getCurrentTimestamp();
            account.setId(UUIDGenerator.generate());
            account.setCreator(username);
            account.setCreateTime(nowTime);
            account.setUpdater(username);
            account.setUpdateTime(nowTime);
            account.setState(DataState.INIT);

            // 4. 执行添加操作
            boolean success = platformAccountService.saveAccount(account);
            return success ? Result.OK(account.getId()) : Result.error("添加失败");
        } catch (Exception e) {
            log.error("添加平台账户失败", e);
            return Result.error("添加失败：" + e.getMessage());
        }
    }

    /**
     * 验证账户信息是否符合平台要求
     */
    private String validateAccount(PlatformAccount account) {
        // 校验平台类型是否为空
        if (account.getPlatformType() == null || account.getPlatformType().trim().isEmpty()) {
            return "平台类型不能为空";
        }

        // 校验名称是否为空
        if (account.getName() == null || account.getName().trim().isEmpty()) {
            return "账户名称不能为空";
        }

        return null;
    }

    /**
     * 检查字符串是否为空
     */
    private boolean isEmpty(String str) {
        return str == null || str.trim().isEmpty();
    }

    /**
     * 更新平台账户
     */
    @PostMapping("/update")
    @ApiOperation("更新平台账户")
    public Result<Object> update(@RequestBody PlatformAccount account) {
        try {
            // 校验ID
            if (account.getId() == null) {
                return Result.error("ID不能为空");
            }

            // 设置更新信息
            String username = getCurrentUsername();
            account.setUpdater(username);
            account.setUpdateTime(DateTimeUtil.getCurrentTimestamp());

            // 执行更新操作
            boolean success = platformAccountService.updateAccount(account);
            return success ? Result.OK() : Result.error("更新失败");
        } catch (Exception e) {
            log.error("更新平台账户失败", e);
            return Result.error("更新失败：" + e.getMessage());
        }
    }

    /**
     * 删除平台账户
     */
    @PostMapping("/delete")
    @ApiOperation("删除平台账户")
    public Result<Object> delete(@RequestBody Map<String, String> params) {
        try {
            // 校验ID
            String id = params.get("id");
            if (id == null) {
                return Result.error("ID不能为空");
            }

            // 执行删除操作
            boolean success = platformAccountService.deleteAccount(id, getCurrentUsername());
            return success ? Result.OK() : Result.error("删除失败");
        } catch (Exception e) {
            log.error("删除平台账户失败", e);
            return Result.error("删除失败：" + e.getMessage());
        }
    }

    /**
     * 批量删除平台账户
     */
    @PostMapping("/batchDelete")
    @ApiOperation("批量删除平台账户")
    public Result<Object> batchDelete(@RequestBody Map<String, List<String>> params) {
        try {
            // 校验ID列表
            List<String> ids = params.get("ids");
            if (ids == null || ids.isEmpty()) {
                return Result.error("ID列表不能为空");
            }

            // 执行批量删除操作
            boolean success = platformAccountService.batchDeleteAccounts(ids, getCurrentUsername());
            return success ? Result.OK() : Result.error("批量删除失败");
        } catch (Exception e) {
            log.error("批量删除平台账户失败", e);
            return Result.error("批量删除失败：" + e.getMessage());
        }
    }

    /**
     * 查询平台账户列表（分页）
     */
    @PostMapping("/query")
    @ApiOperation("查询平台账户列表（分页）")
    public Result<Object> query(@RequestBody Map<String, Object> params) {
        try {
            // 分页参数处理
            Integer pageNo = (Integer) params.getOrDefault("pageNo", 1);
            Integer pageSize = (Integer) params.getOrDefault("pageSize", 10);
            String platformType = (String) params.get("platformType");

            // 构建查询条件
            Page<PlatformAccount> page = new Page<>(pageNo, pageSize);
            QueryWrapper<PlatformAccount> queryWrapper = new QueryWrapper<>();
            queryWrapper.ne("state", 1); // 默认查询未删除的数据

            if (platformType != null && !platformType.isEmpty()) {
                queryWrapper.eq("platform_type", platformType);
            }

            // 执行查询
            IPage<PlatformAccount> resultPage = platformAccountService.page(page, queryWrapper);
            return Result.OK(resultPage);
        } catch (Exception e) {
            log.error("查询平台账户列表失败", e);
            return Result.error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 获取当前登录用户
     */
    private String getCurrentUsername() {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        return sysUser.getUsername();
    }

    /**
     * 自动扫描所有平台并执行数据校验与同步
     * 无需传入参数，自动处理系统中所有已注册的平台
     */
    @PostMapping("/syncAll")
    public Result<Object> syncAllPlatforms(@RequestBody String platformType) {
        try {
            List<PlatformAccount> accountList = platformAccountService.syncPlatformAccounts(platformType);
            // 4. 返回整体处理结果
            return Result.OK("所有平台同步处理完成",accountList);
        } catch (Exception e) {
            return Result.error("同步流程执行失败: " + e.getMessage());
        }
    }
}